package com.diy.sigmund.diyoauth2.common.spring.config;

import com.diy.sigmund.diycommon.entity.po.user.UserAuth;
import com.diy.sigmund.diycommon.entity.po.user.UserBase;
import com.diy.sigmund.diycommon.util.json.JacksonUtil;
import com.diy.sigmund.diyoauth2.mapper.UserAuthMapper;
import com.diy.sigmund.diyoauth2.mapper.UserBaseMapper;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author ylm-sigmund
 * @since 2021/8/23 16:07
 */
@Component(value = "customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(CustomUserDetailsService.class);

    @Resource
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserAuthMapper userAuthMapper;
    @Autowired
    private UserBaseMapper userBaseMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("username is:" + username);
        int countByIdentifier = userAuthMapper.countByIdentifier(username);
        if (countByIdentifier < 1) {
            log.error("the user={} is not found", username);
            throw new UsernameNotFoundException("the user is not found");
        }
        // 线上环境应该通过用户名查询数据库获取加密后的密码
        UserAuth byIdentifier = userAuthMapper.getByIdentifier(username);
        log.info("byIdentifier={}", JacksonUtil.toJson(byIdentifier));
        String password = byIdentifier.getCredential();
        // 用户角色也应在数据库中获取
        UserBase userBase = userBaseMapper.selectByPrimaryKey(byIdentifier.getUserId());
        log.info("userBaseDO={}", JacksonUtil.toJson(userBase));
        String role = userBase.getUserRole();
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(role));
        return new org.springframework.security.core.userdetails.User(username, password, authorities);

    }
}
